﻿﻿# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------------
# Name:        Vkuchinator
# Purpose:
#
# Author:      Trubnikov Sergey
#
# Created:     09.06.2012
# Copyright:   (c) Trubnikov Sergey 2012
# Licence:     GPLv2
# -------------------------------------------------------------------------------

import os, sys, shutil


def indexing_files(path, scan_files=True):
    """Create list with all files in path
    :param path: root path for scan
    :param scan_files: do not indexing files in 'path'
    """
    files_list = []
    if os.path.isdir(path):
        root_list = os.listdir(path)
        if root_list:
            [files_list.append(indexing_files(path + os.sep + I)) for I in root_list]
            return files_list
    else:
        if scan_files:
            return path


def flat_list(item_list):
    """ Convert multi level list to one level list 
    :param item_list: multilevel list
    :rtype : list
    :return : flat list
    """
    files_float_list = []
    for item in item_list:
        if isinstance(item, str):
            files_float_list.append(item)
        elif item is None:
            pass
        elif item:
            files_float_list.extend(flat_list(item))
        else:
            raise TypeError("Expected an str or list type")
    return files_float_list


def start_move(files_list):
    """Move files in list to folders in list"""
    dest = ''
    for I in files_list:
        if os.path.isdir(I):
            dest = I
        else:
            if I != dest + os.sep + os.path.basename(I):
                if os.path.isfile(dest + os.sep + os.path.basename(I)):
                    os.remove(I)
                    print(dest + os.sep + os.path.basename(I) + " = " + I)
                else:
                    shutil.move(I, dest)
                    print("Move '{src}' to '{dst}'".format(src=I, dst="{0}{1}{2}".format(dest, os.sep,
                                                                                         os.path.basename(
                                                                                             I))).decode('cp1251'))
                                                                                                # decode str from cp1251
                                                                                                #  to utf-8


def rm_folders(root):
    """Remove all folders in 'root'"""
    for I in os.listdir(root):
        folder = root + os.sep + I
        if os.path.isdir(folder):
            rm_folders(folder)
            os.rmdir(folder)
            print("Remove empty folder: {0}".format(folder).decode('cp1251'))


def get_path(args):
    if len(args) > 1:
        path = args[1]
    else:
        path = ''
    return path

def main(args):
    files_list = []
    if isinstance(args, str):
        root = args
    else:
        root = get_path(args)
    if os.path.isdir(root):
        for I in os.listdir(root):
            if os.path.isdir(root + os.sep + I):
                files_list.append(root + os.sep + I)
            files_list.append(indexing_files(root + os.sep + I, False))

        for I in range(files_list.count(None)):
            files_list.remove(None)
        start_move(flat_list(files_list))

        for I in os.listdir(root):
            if os.path.isdir(root + os.sep + I):
                rm_folders(root + os.sep + I)
    else:
        print("'%s' is not a valid directory" % root.decode('cp1251'))
        return 1

    return 0


if __name__ == '__main__':
    main(sys.argv)
